const Router = require('koa-router');
const { authenticateUser, verifyToken } = require('../middleware/auth');
const fileController = require('../controllers/fileController');
const dirController = require('../controllers/dirController');

const router = new Router();
router.prefix('/api');

// 用户认证
router.post('/users/login', async (ctx) => {
  const { username, password } = ctx.request.body;
  const loginResult = authenticateUser(username, password);

  if (loginResult.success) {
    // 认证成功，返回 token 和用户信息
    ctx.body = {
      status: 0,
      msg: '登录成功',
      token: loginResult.token // 返回 token
    };
  } else {
    ctx.status = 401;
    ctx.body = { status: 1, msg: '用户名或密码错误' };
  }
});

// 中间件：验证 token
async function verifyAuth(ctx, next) {
  const token = ctx.headers['authorization']?.split(' ')[1]; // 从请求头获取 token

  if (!token) {
    ctx.status = 401;
    ctx.body = { status: 1, msg: '未提供 token' };
    return;
  }

  const result = verifyToken(token);

  if (result.valid) {
    ctx.state.user = result.decoded;  // 设置用户信息
    ctx.state.currentDir = result.decoded.currentDir;  // 设置当前目录
    await next();  // 继续处理请求
  } else {
    ctx.status = 401;
    ctx.body = { status: 1, msg: result.message }; // token 无效
  }
}

// 所有文件和目录相关的操作都需要验证用户身份
router.use(verifyAuth);

// 文件操作
router.post('/files/upload', fileController.uploadFile);
router.get('/files/download/:filename', fileController.downloadFile);
router.delete('/files/delete/:filename', fileController.deleteFile);
router.put('/files/rename', fileController.renameFile);

// 目录操作
router.post('/dirs/create', dirController.createDirectory);
//router.delete('/dirs/delete', dirController.deleteDirectory);
//router.put('/dirs/rename', dirController.renameDirectory);
router.get('/dirs/list', dirController.listDirectory);
router.put('/dirs/change', dirController.changeDirectory);
router.get('/dirs/pwd', dirController.getCurrentDirectory);

module.exports = router;


